package cn.honglian.basic.interceptor;

import cn.honglian.basic.anno.PreAuthorize;
import cn.honglian.system.mapper.PermissionMapper;
import cn.honglian.user.domain.Logininfo;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 3.1.设置编码字符集
        response.setCharacterEncoding("UTF-8");
        // 3.2.设置响应参数类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        // 获取请求头里的token
        String token = request.getHeader("token");

        if (Strings.isNotBlank(token)) {
            // 再判断 redis中的logininfo是否能取到
            Logininfo logininfoo = (Logininfo) redisTemplate.opsForValue().get(token);
            if (null != logininfoo) {
                // 获取请求方法的对象
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                // 获取方法对象中的方法注解
                PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                // 获取打注解中的sn
                if (null != preAuthorize) {
                    String sn = preAuthorize.sn();
                    // 获取用户的权限   // 获取到redis中的权限
                    List<String> per = permissionMapper.findByLogininfoId(logininfoo.getId());
                    if (!per.contains(sn)) {
                        // 3.3.获取到打印流,并设置响应数据
                        PrintWriter writer = response.getWriter();
                        writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
                        // 3.4.刷新、关流
                        writer.flush();
                        writer.close();
                        return false;
                    }
                }
                // 有值则重新设置过期时间
                redisTemplate.expire(token, 30, TimeUnit.MINUTES);
                return true;
            }
        }

        // 3.如果能走到这里，说明token为空或者是Redis中用户信息为空，那么以未登录进行处理

        // 3.3.获取到打印流,并设置响应数据
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
        // 3.4.刷新、关流
        writer.flush();
        writer.close();
        return false;
    }
}
